package com.hunttown.mes.common.amap;

import com.hunttown.mes.common.http.HttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @title: 高德地图工具类
 * @author: wangjunfu
 * @date: 2021年04月08日 12:33
 * @description:
 */
public class AmapUtils {

    /**
     * 获取POI信息
     *
     * @param city    城市
     * @param keyword 关键字
     * @return json
     */
    public static String getPoi(String city, String keyword) {
        String url = "https://restapi.amap.com/v3/place/text?";

        List<String> param = new ArrayList<>();
        param.add("key=" + AmapConstants.AmapKey);
        param.add("keywords=" + keyword);
        param.add("city=" + city);
        param.add("citylimit=true");

        url = url + String.join("&", param);

        return HttpClient.doGet(url);
    }

    /**
     * 获取地理编码
     *
     * @param city    城市
     * @param keyword 关键字
     * @return json
     */
    public static String getGeo(String city, String keyword) {
        String url = "https://restapi.amap.com/v3/geocode/geo?";

        List<String> param = new ArrayList<>();
        param.add("key=" + AmapConstants.AmapKey);
        param.add("address=" + keyword);
        param.add("city=" + city);

        url = url + String.join("&", param);

        String res = HttpClient.doGet(url);
        JSONObject jsonObject = new JSONObject(res);

        Object statecode = jsonObject.get("status");
        if (statecode.equals("0")) {
            return "";
        }

        if (jsonObject.has("geocodes")) {
            JSONArray geoObject = jsonObject.getJSONArray("geocodes");

            if (geoObject.toList().size() > 0) {
                Object geoStr = geoObject.get(0);
                JSONObject codeObject = new JSONObject(geoStr.toString());

                if (codeObject.has("location")) {
                    Object location = codeObject.get("location");
                    return location.toString();
                }
            }
        }

        return "";
    }

    /**
     * 获取输入提示
     *
     * @param city    城市
     * @param keyword 关键字
     * @return json
     */
    public static String getTips(String city, String keyword) {
        String url = "https://restapi.amap.com/v3/assistant/inputtips?";

        List<String> param = new ArrayList<>();
        param.add("key=" + AmapConstants.AmapKey);
        param.add("keywords=" + keyword);
        param.add("city=" + city);
        param.add("citylimit=true");

        url = url + String.join("&", param);

        return HttpClient.doGet(url);
    }

    public static void main(String[] arr) {
        //System.out.println(getPoi("威海", "哈尔滨工业大学"));
        //System.out.println(getTips("威海", "哈尔滨工业大学"));
        String s = getGeo("威海", "哈尔滨工业大学");
        System.out.println(s);
    }
}
